/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Reportes;

import Complementos.Conexion_BD;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.*;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

/**
 *
 * @author COMPUTER
 */
public class FrmReporte extends javax.swing.JFrame {

    Conexion_BD con = new Conexion_BD();
    ResultSet rs = null;
    int j=0;

    /**
     * Creates new form Reportes
     */
    public FrmReporte() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame2 = new javax.swing.JFrame();
        objectTable1 = new org.jfree.util.ObjectTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        cbxtipo = new javax.swing.JComboBox();

        javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
        jFrame2.getContentPane().setLayout(jFrame2Layout);
        jFrame2Layout.setHorizontalGroup(
            jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame2Layout.setVerticalGroup(
            jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("..::  Sonrisas Tools :..    Reportes");

        jPanel1.setBackground(new java.awt.Color(204, 204, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 153)), "Reportes", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tunga", 0, 24), new java.awt.Color(255, 255, 153))); // NOI18N

        jLabel1.setText("Seleccione");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Media/grafico.gif"))); // NOI18N
        jButton1.setText("Graficar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        cbxtipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione", "Comparacion por sexo", "comparacion distrito", "Grafico de barras" }));
        cbxtipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbxtipoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(69, 69, 69)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37)
                .addComponent(cbxtipo, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(55, 55, 55)
                .addComponent(jButton1)
                .addContainerGap(114, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbxtipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(257, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        int opcion = cbxtipo.getSelectedIndex();
        
        if (opcion == 0) {
            JOptionPane.showMessageDialog(this, "Seleccione una opcion");
        } else {
            switch (opcion) {
                case 1:
            try {
                genero();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(FrmReporte.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DocumentException ex) {
                Logger.getLogger(FrmReporte.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(FrmReporte.class.getName()).log(Level.SEVERE, null, ex);
            }
                    break;
                case 2:
                    distrito();
                    break;
                case 3:
                    graficoBarrasPorGenero();
                    break;
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cbxtipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxtipoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbxtipoActionPerformed

    public void distrito() {
        int i = 0, suma = 0;
        double lima = 0, chorrillos = 0, lurigancho = 0;

        String[] sexo = new String[4];
        String query = "select idUbigeo,count(idUbigeo) from persona group by idUbigeo";
        // System.out.println(query); //imprimir query

        DecimalFormat format = new DecimalFormat("##.##"); //dar formato de dos DEcimales al Resultado

        try {
            con.Conectar();
            rs = con.Consultar(query);
            while (rs.next()) { //tiene dos filas con dos campos
                sexo[i] = rs.getString(2); //el numero esta en la columno 2
                suma = suma + Integer.parseInt(sexo[i]);
                i++;
            }

            // System.out.println(suma);//verificar


            lima = (Double.parseDouble(sexo[0]) / suma) * 100; //Reales
            chorrillos = (Double.parseDouble(sexo[1]) / suma) * 100;
            lurigancho = (Double.parseDouble(sexo[1]) / suma) * 100;





            rs.close();
            con.Desconectar();
        } catch (Exception ex) {
            Logger.getLogger(FrmReporte.class.getName()).log(Level.SEVERE, null, ex);
        }

        DefaultPieDataset dataset = new DefaultPieDataset(); //creando un objeto q pide enviarle valores

        dataset.setValue("Lima " + format.format(lima) + "%" + "\n" + Integer.parseInt(sexo[0]), Integer.parseInt(sexo[0]));  // seteando valores masculino       
        dataset.setValue("chorrillos " + format.format(chorrillos) + "%" + "\n" + Integer.parseInt(sexo[1]), Integer.parseInt(sexo[1]));   //seteando valores  femenino
        dataset.setValue("lurigancho " + format.format(lurigancho) + "%" + "\n" + Integer.parseInt(sexo[2]), Integer.parseInt(sexo[2]));

        JFreeChart grafico = ChartFactory.createPieChart3D("Reporte por DISTRITO", dataset, true, true, false);
        //crear piechart3D m titulo,data set datos enviados, true, true son dos valores,                        
        // Creación del panel con el gráfico
        ChartPanel panel = new ChartPanel(grafico); //crea un objeto de la clase 
        //constructor 

        JFrame Ventana = new JFrame("Reportes");
        Ventana.getContentPane().add(panel);
        Ventana.pack();
        Ventana.setVisible(true);
        //   ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        /*
         * try { ChartUtilities.saveChartAsJPEG(new File("graficos/grafico'" + i
         * + "'.jpg"), chart, 500, 300); } catch (IOException ex) {
         * Logger.getLogger(reporte.class.getName()).log(Level.SEVERE, null,
         * ex); }
         */

    }

    public void genero() throws FileNotFoundException, DocumentException, IOException {
        int i = 0, suma = 0;
        double hombre = 0, mujer = 0;
        String[] sexo = new String[4];
        String query = "select genero,count(genero) from persona pe, paciente pa where pe.idPERSONA = pa.idPERSONA group by genero";
        // System.out.println(query); //imprimir query

        DecimalFormat format = new DecimalFormat("##.##"); //dar formato de dos DEcimales al Resultado
        try {
            con.Conectar();
            rs = con.Consultar(query);
            System.out.println("entroooo");
            while (rs.next()) { //tiene dos filas con dos campos
                sexo[i] = rs.getString(2); //el numero esta en la columno 2
                suma = suma + Integer.parseInt(sexo[i]);
                i++;
            }
            // System.out.println(suma);//verificar

            mujer = (Double.parseDouble(sexo[0]) / suma) * 100; //Reales
            hombre = (Double.parseDouble(sexo[1]) / suma) * 100;

            rs.close();
            con.Desconectar();
        } catch (Exception ex) {
            Logger.getLogger(FrmReporte.class.getName()).log(Level.SEVERE, null, ex);
        }

        DefaultPieDataset dataset = new DefaultPieDataset(); //creando un objeto q pide enviarle valores


        dataset.setValue("Masculino " + format.format(hombre) + "%", Integer.parseInt(sexo[1]));  // seteando valores masculino       
        dataset.setValue("Femenino " + format.format(mujer) + "%", Integer.parseInt(sexo[0]));   //seteando valores  femenino


        JFreeChart grafico = ChartFactory.createPieChart3D("Reporte por GENERO", dataset, true, true, false);

        //crear piechart3D m titulo,data set datos enviados, true, true son dos valores,                        
        // Creación del panel con el gráfico
        ChartPanel panel = new ChartPanel(grafico); //crea un objeto de la clase 
        //constructor 




        JFrame Ventana = new JFrame("Reportes");
        Ventana.getContentPane().add(panel);
        Ventana.pack();
        Ventana.setVisible(true);
        //   ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try {
            ChartUtilities.saveChartAsJPEG(new File("D:\\Sonrisas Tools\\ProyectoSonrisas\\src\\graficos\\grafico'" + j + "'.jpg"), grafico, 500, 300);
            j++;
        } catch (IOException ex) {
            Logger.getLogger(FrmReporte.class.getName()).log(Level.SEVERE, null,
                    ex);
        }
if (grafico != null) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream("D:\\Sonrisas Tools\\ProyectoSonrisas\\src\\graficos\\diego.pdf")); 
                
            //convert chart to PDF with iText:
            Rectangle pagesize = new Rectangle(500, 500); 
            com.lowagie.text.Document document = new com.lowagie.text.Document(pagesize, 50, 50, 50, 50); 
            try { 
                PdfWriter writer = PdfWriter.getInstance(document, out); 
                document.addAuthor("JFreeChart"); 
                document.open(); 
        
                PdfContentByte cb = writer.getDirectContent(); 
                PdfTemplate tp = cb.createTemplate(500, 500); 
                Graphics2D g2 = tp.createGraphics(500, 500, new DefaultFontMapper()); 
        
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 450, 500);
                grafico.draw(g2, r2D, null); 
                g2.dispose(); 
                cb.addTemplate(tp, 0, 0); 
            } finally {
                document.close(); 
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }}
    }

    public void graficoBarrasPorGenero() {
        int i = 0, suma = 0;
        double hombre = 0, mujer = 0;
        String[] sexo = new String[4];
        String query = "select genero,count(genero) from persona pe, paciente pa where pe.idPERSONA = pa.idPERSONA group by genero";
        // System.out.println(query); //imprimir query

        DecimalFormat format = new DecimalFormat("##.##"); //dar formato de dos DEcimales al Resultado
        try {
            con.Conectar();
            rs = con.Consultar(query);
            System.out.println("entroooo");
            while (rs.next()) { //tiene dos filas con dos campos
                sexo[i] = rs.getString(2); //el numero esta en la columno 2
                suma = suma + Integer.parseInt(sexo[i]);
                i++;
            }
            // System.out.println(suma);//verificar

            mujer = (Double.parseDouble(sexo[0]) / suma) * 100; //Reales
            hombre = (Double.parseDouble(sexo[1]) / suma) * 100;

            rs.close();
            con.Desconectar();
        } catch (Exception ex) {
            Logger.getLogger(FrmReporte.class.getName()).log(Level.SEVERE, null, ex);
        }


        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        dataset.setValue(Integer.parseInt(sexo[1]), "Masculino " + format.format(hombre) + "%", "Masculino");  // seteando valores masculino       
        dataset.setValue(Integer.parseInt(sexo[0]), "Femenino " + format.format(mujer) + "%", "Femenino ");   //seteando valores  femenino

        JFreeChart grafico = ChartFactory.createBarChart3D("Reporte por GENERO",
                "Porcentaje por genero",
                "cantidad de registrados",
                dataset,
                PlotOrientation.VERTICAL,
                true, true, false);


        ChartPanel panel = new ChartPanel(grafico); //crea un objeto de la clase 
        //constructor         




        JFrame Ventana = new JFrame("Reportes");
        Ventana.getContentPane().add(panel);
        Ventana.pack();
        Ventana.setVisible(true);


    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmReporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmReporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmReporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmReporte.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FrmReporte().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cbxtipo;
    private javax.swing.JButton jButton1;
    private javax.swing.JFrame jFrame2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private org.jfree.util.ObjectTable objectTable1;
    // End of variables declaration//GEN-END:variables
}
